package com.sophialex.health.record.common.showKtable;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.widgets.Display;

import com.sophialex.health.common.platform.Store;
import com.sophialex.health.common.platform.SuperContext;
import com.sophialex.health.record.common.Messages;
import com.sophialex.health.record.common.util.SystemUtil;
import com.sophialex.health.system.frame.resource.RcpResourceManager;
import com.sophialex.health.system.frame.util.Assert;
import com.sophialex.health.system.frame.util.NumberUtil;
import de.kupzog.ktable.KTable;
import de.kupzog.ktable.KTableCellEditor;
import de.kupzog.ktable.KTableCellRenderer;
import de.kupzog.ktable.KTableSortedModel;
import de.kupzog.ktable.SWTX;
import de.kupzog.ktable.editors.KTableCellEditorText;
import de.kupzog.ktable.renderers.CheckableCellRenderer;
import de.kupzog.ktable.renderers.FixedCellRenderer;
import de.kupzog.ktable.renderers.TextCellRenderer;

/**
 * 动态行列和行列转换的表格总数据模型
 * 
 * @author Administrator
 * 
 */
public class DynamicReportTableModel extends KTableSortedModel {

	protected String key;
	public boolean haveCheckbox = false;// 第一列为Checkbox

	private Font HeaderFont = SuperContext.f10;
	private Font font = SystemUtil.tabFont;

	static Color red = new Color(Display.getDefault(), new RGB(255, 0, 0));

	private Color BGROWFOCUS = new Color(Display.getDefault(), new RGB(119, 158,245)); 

	private Color Foreground = SystemUtil.Table_color;
	private Color backgroundColor = SystemUtil.Table_Background;
	private Color rowBackgroundColor = SystemUtil.Table_GroupBackground;
	private Color rowColor = SystemUtil.Table_Groupcolor;
	private int rowHeight = SystemUtil.Table_Height;

	private HeaderCellRenderer m_FixedRenderer = new HeaderCellRenderer(
			FixedCellRenderer.STYLE_FLAT | FixedCellRenderer.INDICATION_SORT
					| FixedCellRenderer.INDICATION_FOCUS
					| FixedCellRenderer.INDICATION_CLICKED);
	private final TextCellRenderer m_textRenderer = new TextCellRenderer(
			TextCellRenderer.INDICATION_FOCUS_ROW);

	private KTableCellRenderer m_CheckableRenderer = new CheckableCellRenderer(
			CheckableCellRenderer.INDICATION_CLICKED
					| CheckableCellRenderer.INDICATION_FOCUS);

	public Map<Integer, String[]> columMap = new HashMap<Integer, String[]>();// 表头
	private int rowCount = 1;
	private int columnCount = 1;
	private int fixRowCount = 1;
	private int fixColCount = 0;
	public final static Color Table_Column_Color = RcpResourceManager.getColor(
			224, 239, 235);

	private KTable kTable;

	// 需要隐藏的列 true显示；false不显示
	private String[] hidedCols = null;

	// 不显示0
	private boolean hideZero = true;

	// 是否横纵转换
	private boolean vector = false;

	// 是否多表头
	private boolean multiTitle = false;

	private Map<Integer, Integer> columAlignment;// 表头排序

	// 默认的宽度
	private Map<Integer, Integer> dftWidth;

	// 当前记忆的宽度
	private String[] widths;

	// 最后一行是否合计项
	private boolean isEndSum;

	/*
	 * 第一列为Checkbox
	 */
	public void setHaveCheckbox(boolean haveCheckbox) {
		this.haveCheckbox = haveCheckbox;
	}

	public boolean isMultiTitle() {
		return multiTitle;
	}

	public void setMultiTitle(boolean multiTitle) {
		this.multiTitle = multiTitle;
	}

	public boolean isHideZero() {
		return hideZero;
	}

	public String[] getHidedCols() {
		return hidedCols;
	}

	public void setHidedCols(String[] hidedCols) {
		this.hidedCols = hidedCols;
	}

	public boolean isVector() {
		return vector;
	}

	public void setVector(boolean vector) {
		this.vector = vector;
	}

	public void setHideZero(boolean hideZero) {
		this.hideZero = hideZero;
	}

	public DynamicReportTableModel(KTable kTable, String key,
			Map<Integer, Integer> dftWidth, Map<Integer, Integer> columAlignment) {
		this.kTable = kTable;
		this.key = key;
		widths = Store.getColumnWidth(key + vector);

		this.dftWidth = dftWidth;
		this.columAlignment = columAlignment;

		m_FixedRenderer.setAlignment(SWTX.ALIGN_HORIZONTAL_CENTER
				| SWTX.ALIGN_VERTICAL_CENTER | SWTX.WRAP);

		m_FixedRenderer.setFont(HeaderFont);

		m_textRenderer.setFont(font);

		m_textRenderer.COLOR_BGROWFOCUS = BGROWFOCUS;
	}

	public DynamicReportTableModel(KTable kTable, String key,
			Map<Integer, Integer> dftWidth,
			Map<Integer, Integer> columAlignment, boolean isEndSum) {
		this.kTable = kTable;
		this.key = key;
		this.isEndSum = isEndSum;
		widths = Store.getColumnWidth(key + vector);

		this.dftWidth = dftWidth;
		this.columAlignment = columAlignment;

		m_FixedRenderer.setAlignment(SWTX.ALIGN_HORIZONTAL_CENTER
				| SWTX.ALIGN_VERTICAL_CENTER | SWTX.WRAP);

		m_FixedRenderer.setFont(HeaderFont);

		m_textRenderer.setFont(font);

		m_textRenderer.COLOR_BGROWFOCUS = BGROWFOCUS;
	}

	public Map<Integer, String[]> getColumMap() {
		return columMap;
	}

	public void setColumMap(Map<Integer, String[]> columMap) {
		this.columMap = columMap;
	}

	/*
	 * @str数据值
	 * 
	 * @vector是否行列转换
	 * 
	 * @multiTitle是否多表头
	 */
	public void setData(String[][] str, boolean vector) {
		if (this.vector != vector) {
			widths = Store.getColumnWidth(key + vector);
			if (Store.store.contains(Store.COLUMN_WIDTH + key + vector
					+ "hidedCols")) { //$NON-NLS-1$
				hidedCols = Store.getColumnWidth(key + vector + "hidedCols"); //$NON-NLS-1$
			} else {
				hidedCols = null;
			}
		}
		this.vector = vector;
		columMap.clear();

		if (str != null && str.length > 0 && str[0] != null
				&& str[0].length > 0) {

			// 行列转换
			if (vector) {
				str = NumberUtil.changStr(str);
				str[0][0] = Messages.DynamicReportTableModel_2;
			}

			int i = 0;
			for (String[] column : str) {
				if (!vector && multiTitle) {
					if (i == 0) {
						// 判断是否有多行标题，以"|"分隔
						multiTitle = false;
						for (int a = 0; column != null && a < column.length; a++) {
							if (!Assert.isNull(column[a])
									&& column[a].indexOf("|") > 0) { //$NON-NLS-1$
								multiTitle = true;
							}
						}
						if (multiTitle) {
							columMap.put(i, column);
							i++;
						}
					}
					columMap.put(i, column);
				} else {
					columMap.put(i, column);
				}
				i++;
			}
			if (!vector) {
				fixColCount = 1;
				rowCount = columMap.size();
				columnCount = str[0].length;
				fixRowCount = 1;
				if (multiTitle) {
					fixRowCount++;
				}
			} else {
				fixColCount = 1;
				rowCount = columMap.size();
				columnCount = str[0].length;
				fixRowCount = 1;
			}
		} else {
			rowCount = 0;
			columnCount = 0;
			fixColCount = 0;
			fixRowCount = 0;
		}

		initialize();
		// kTable.setBounds(0, 0, 800, 600);
		kTable.redraw();
	}

	/*
	 * 处理数据
	 * 
	 * @filterRows 去掉没有意义的行
	 * 
	 * @filterCols去掉没有意义的列
	 * 
	 * @addSumDate是否添加合计项
	 */
	public static String[][] chargDate(String[][] str, String[] filterCols,
			int[] filterRows, boolean addSumDate) {
		if (str != null && str.length > 0 && str[0] != null
				&& str[0].length > 0) {
			// 去掉没有意义的行和列
			if ((filterCols != null && filterCols.length > 0)
					|| (filterRows != null && filterRows.length > 0)) {
				str = filterSomeRows(str, filterRows, filterCols);
			}

			// 添加合计项
			if (addSumDate && str != null && str.length > 0 && str[0] != null
					&& str[0].length > 0) {
				String[][] strSum = new String[str.length + 1][str[0].length];
				for (int a = 0; a < str[0].length; a++) {// 列
					for (int i = 0; i < str.length; i++) {// 行
						strSum[i][a] = str[i][a];
						if (a > 0 && i > 0 && !Assert.isNull(str[i][a])) {
							if (Assert.isNull(strSum[str.length][a])) {
								strSum[str.length][a] = "0"; //$NON-NLS-1$
							}
							try {
								strSum[str.length][a] = (Double
										.valueOf(strSum[str.length][a]) + Double
										.valueOf(str[i][a]))
										+ ""; //$NON-NLS-1$
							} catch (Exception e) {
								// 该列不为数字行，不能计算合计
								strSum[str.length][a] = Messages.DynamicReportTableModel_6;
								break;
							}
						}
					}
				}
				strSum[str.length][0] = Messages.DynamicReportTableModel_7;
				str = strSum;
			}
		}
		return str;
	}

	@Override
	public KTableCellEditor doGetCellEditor(int col, int row) {
		if ((!(haveCheckbox && col == 0 && (!isEndSum || row < this.rowCount - 1)))
				&& row >= getFixedHeaderRowCount()) {
			return new KTableCellEditorText();
		}
		return null;
	}

	// @Override
	// public KTableCellRenderer doGetCellRenderer(int col, int row) {
	// if (row < getFixedHeaderRowCount()) {
	// m_textRenderer.setBackground(Table_Column_Color);
	// } else {
	// m_textRenderer.setBackground(RcpResourceManager
	// .getColor(SWT.COLOR_WHITE));
	// }
	// if (row < fixRowCount) {
	// m_textRenderer.setAlignment(SWTX.ALIGN_HORIZONTAL_CENTER
	// | SWTX.ALIGN_VERTICAL_CENTER);
	// } else {
	//
	// if (col >= fixColCount) {
	// m_textRenderer.setAlignment(SWTX.ALIGN_HORIZONTAL_RIGHT
	// | SWTX.ALIGN_VERTICAL_CENTER);
	// } else {
	// m_textRenderer.setAlignment(SWTX.ALIGN_HORIZONTAL_LEFT
	// | SWTX.ALIGN_VERTICAL_CENTER);
	// }
	// }
	// return m_textRenderer;
	// }

	@Override
	public KTableCellRenderer doGetCellRenderer(int col, int row) {
		if (haveCheckbox && col == 0 && row >= getFixedHeaderRowCount()
				&& (!isEndSum || row < this.rowCount - 1)) {
			return m_CheckableRenderer;
		}
		if (isHeaderCell(col, row)) {
			// 表头
			m_FixedRenderer.setFont(HeaderFont);
			return m_FixedRenderer;
		}

		if (row < fixRowCount) {
			m_textRenderer.setAlignment(SWTX.ALIGN_HORIZONTAL_CENTER
					| SWTX.ALIGN_VERTICAL_CENTER);
		} else {
			if (columAlignment != null && columAlignment.get(col) != null) {
				m_textRenderer.setAlignment(columAlignment.get(col)
						| SWTX.ALIGN_VERTICAL_CENTER);
			} else {
				m_textRenderer.setAlignment(SWTX.ALIGN_HORIZONTAL_RIGHT
						| SWTX.ALIGN_VERTICAL_CENTER);
			}
			// if (col >= fixColCount) {
			// m_textRenderer.setAlignment(SWTX.ALIGN_HORIZONTAL_RIGHT
			// | SWTX.ALIGN_VERTICAL_CENTER);
			// } else {
			// m_textRenderer.setAlignment(SWTX.ALIGN_HORIZONTAL_LEFT
			// | SWTX.ALIGN_VERTICAL_CENTER);
			// }
		}

		m_textRenderer.setFont(font);
		m_textRenderer.setForeground(Foreground);
		m_textRenderer.setBackground(backgroundColor);

		if ((row - fixRowCount) % 2 == 0) {
			m_textRenderer.setBackground(rowBackgroundColor);
			m_textRenderer.setForeground(rowColor);
		}
		return m_textRenderer;
	}

	@Override
	public int doGetColumnCount() {
		return columnCount;
	}

	@Override
	public Point doBelongsToCell(int col, int row) {
		if (row < fixRowCount && columMap != null) {
			if (fixRowCount > 1) {
				String[] str = columMap.get(row);
				if (str[col] != null && str[col].trim().indexOf("|") > 0) { //$NON-NLS-1$
					if (row == 0
							&& col > 0
							&& doGetContentAt(col, row).equals(
									doGetContentAt(col - 1, row))) {
						col--;
					}
				} else if (row == 1) {
					row--;
				}
			}
			return new Point(col, row);
		} else {
			return new Point(col, row);
		}
	}

	@Override
	public Object doGetContentAt(int col, int row) {
		if (columMap == null) {
			return ""; //$NON-NLS-1$
		}
		String[] str = columMap.get(row);
		if (str == null || str.length - 1 < col) {
			return ""; //$NON-NLS-1$
		}
		// return str[col];
		if (haveCheckbox && col == 0 && row >= getFixedHeaderRowCount()
				&& (!isEndSum || row < this.rowCount - 1)) {
			return str[col] != null && str[col].equals("1"); //$NON-NLS-1$
		}

		if (str[col] == null) {
			return ""; //$NON-NLS-1$
		}

		String cellValue = ""; //$NON-NLS-1$
		if (str != null) {
			if (row < fixRowCount) {
				cellValue = getItemSortName(str[col], row);
				return cellValue;
			}
			if (col < str.length) {
				if (row >= fixRowCount && col >= fixColCount) {
					try {
						Double d = Double.valueOf(str[col]);
						if (hideZero && d.equals(0d)) {
							cellValue = ""; //$NON-NLS-1$
							return cellValue;
						}
						cellValue = NumberUtil.getSimFormatValue(d, 2);
					} catch (Exception e) {
						cellValue = str[col];
					}
					return cellValue;
				}
				cellValue = str[col];
				return cellValue;
			}
		}
		return cellValue;
	}

	private String getItemSortName(String sortCode, int row) {
		if (sortCode != null && fixRowCount > 1) {
			if (sortCode.trim().indexOf("|") > 0 && row == 0) { //$NON-NLS-1$
				int beginIndex = sortCode.indexOf("|"); //$NON-NLS-1$
				return sortCode.substring(0, beginIndex);
			} else if (sortCode.trim().indexOf("|") > 0 && row == 1) { //$NON-NLS-1$
				int beginIndex = sortCode.indexOf("|"); //$NON-NLS-1$
				return sortCode.substring(beginIndex + 1, sortCode.length());
			}
		}
		return sortCode;
	}

	@Override
	public int doGetRowCount() {
		return rowCount;
	}

	@Override
	public void doSetContentAt(int col, int row, Object value) {
		if (haveCheckbox && col == 0 && row >= getFixedHeaderRowCount()
				&& (!isEndSum || row < this.rowCount - 1)) {
			if (columMap == null) {
				return;
			}
			String[] str = columMap.get(row);
			if (str == null || str.length - 1 < col) {
				return;
			}
			str[col] = ((Boolean) value && value != null) ? "1" : "0"; //$NON-NLS-1$ //$NON-NLS-2$
		}
	}

	@Override
	public int getInitialColumnWidth(int column) {
		if (hidedCols != null
				&& Arrays.binarySearch(hidedCols, column + "") >= 0) { //$NON-NLS-1$
			return 0;
		} else {
			if (widths != null && column < widths.length) {
				try {
					return Integer.parseInt(widths[column]) == 0 ? 80 : Integer
							.parseInt(widths[column]);
				} catch (NumberFormatException e) {
					return getDefaultWidth(column);
				}
			} else {
				return getDefaultWidth(column);
			}
		}
	}

	public int getDefaultWidth(int column) {
		if (dftWidth != null && dftWidth.get(column) != null) {
			return dftWidth.get(column) == 0 ? 80 : dftWidth.get(column);
		} else {
			return 80;
		}
	}

	public void saveStore() {
		if (getColumnCount() > 1) {
			Store.saveColumnWIdth(key + vector, getColumnWidth());
		}
	}

	public String getColumnWidth() {
		int column = getColumnCount();
		StringBuffer buffer = new StringBuffer(""); //$NON-NLS-1$
		for (int i = 0; i < column; i++) {
			if (i == 0) {
				buffer.append(getColumnWidth(i));
			} else {
				buffer.append(Store.SEPARTER).append(getColumnWidth(i));
			}
		}
		return buffer.toString();
	}

	@Override
	public int getInitialRowHeight(int row) {
		if (row < getFixedHeaderRowCount()) {
			return 24;
		}
		return this.rowHeight;
	}

	public int getFixedHeaderColumnCount() {
		return 0;
	}

	public int getFixedHeaderRowCount() {
		return fixRowCount;
	}

	public int getFixedSelectableColumnCount() {
		return fixColCount;
	}

	public int getFixedSelectableRowCount() {
		return 0;
	}

	public int getRowHeightMinimum() {
		return 24;
	}

	public boolean isColumnResizable(int col) {
		// if (col == 0 && !vector && !ShowKh)
		// {
		// return false;
		// }
		if (hidedCols != null && Arrays.binarySearch(hidedCols, col + "") >= 0) { //$NON-NLS-1$
			return false;
		}
		return true;
	}

	public boolean isRowResizable(int row) {
		return true;
	}

	public void setRowCount(int rowCount) {
		this.rowCount = rowCount;
	}

	public void setColumnCount(int columnCount) {
		this.columnCount = columnCount;
	}

	public void setFixRowCount(int fixRowCount) {
		this.fixRowCount = fixRowCount;
	}

	public void setFixColCount(int fixColCount) {
		this.fixColCount = fixColCount;
	}

	// rows里是索引
	private static String[][] filterSomeRows(String[][] array, int[] rows,
			String[] colsString) {
		List<String[]> result = new ArrayList<String[]>();
		String[] resultcol = null;
		Integer[] cols = null;
		if (colsString != null && colsString.length > 0) {
			List<Integer> colsList = new ArrayList<Integer>();
			for (int i = 0; array != null && array.length > 0
					&& i < array[0].length; i++) {
				if (array[0][i] != null) {
					for (int j = 0; j < colsString.length; j++) {
						if (array[0][i].contains(colsString[j])) {
							colsList.add(i);
							break;
						}
					}
				}
			}
			cols = colsList.toArray(new Integer[] {});
		}
		for (int i = 0; array != null && i < array.length; i++) {
			if (rows != null && rows.length > 0
					&& Arrays.binarySearch(rows, i) >= 0) {
				continue;
			} else if (cols == null || cols.length < 1) {
				result.add(array[i]);
			} else if (array[i] != null && array[i].length > cols.length) {
				if (i == 0) {

				}
				resultcol = new String[array[i].length - cols.length];
				int a = 0;
				for (int j = 0; array[i] != null && j < array[i].length; j++) {
					if (Arrays.binarySearch(cols, j) >= 0) {
						continue;
					} else {
						resultcol[a] = array[i][j];
						a++;
					}
				}
				result.add(resultcol);
			}
		}
		return result.toArray(new String[][] {});

	}

	// rows里是索引
	private String[][] filterSomeRows(String[][] array, int[] rows, int[] cols) {
		Arrays.sort(rows);
		List<String[]> result = new ArrayList<String[]>();
		String[] resultcol = null;
		for (int i = 0; array != null && i < array.length; i++) {
			if (Arrays.binarySearch(rows, i) >= 0) {
				continue;
			} else if (cols == null || cols.length < 1) {
				result.add(array[i]);
			} else if (array[i] != null && array[i].length > cols.length) {
				resultcol = new String[array[i].length - cols.length];
				int a = 0;
				for (int j = 0; array[i] != null && j < array[i].length; j++) {
					if (Arrays.binarySearch(cols, j) >= 0) {
						continue;
					} else {
						resultcol[a] = array[i][j];
						a++;
					}
				}
				result.add(resultcol);
			}
		}
		return result.toArray(new String[][] {});

	}
}
